package utils

import (
	"encoding/json"
	"crypto/tls"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"io/ioutil"
	"net/http"
)

type HttpUtil struct{

}

func (this *HttpUtil) ParseJsonToStruct(url string, strc interface{}) {
	req := httplib.Get(url)
	str, err := req.String()
	if err != nil {
		beego.Error(err)
	}

	err = json.Unmarshal([]byte(str), strc)
}

func (this *HttpUtil) ParseJsonToStructFromHttps(url string, strc interface{}) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Get(url)
	defer resp.Body.Close()
	if err != nil {
		beego.Error("error:", err)
		return
	}

	body, err := ioutil.ReadAll(resp.Body)

	err = json.Unmarshal(body, strc)
}

func (this *HttpUtil) PostJson(url string ,json  string) {
	req := httplib.Post(url)
	req.Header("Content-type","application/json")
	req.Body(json)
	str, err := req.String()
	beego.Info(str)
	CheckErr(err)
}

func (this *HttpUtil) DeleteProtocol(url string) {
	req := httplib.Delete(url)
	_, err := req.String()
	CheckErr(err)
}

func (this *HttpUtil) PostUrl(url string) {
	req := httplib.Post(url)
	_, err := req.String()
	CheckErr(err)
}